package middelware

import (
	"gitee.com/qian/guser/library/response"
	"gitee.com/qian/guser/model"
	"gitee.com/qian/guser/shared"
	"github.com/gogf/gcache-adapter/adapter"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gcache"
)

var GUserTokenMiddleware = middlewareService{}

type middlewareService struct {
}

// 自定义上下文对象
func (s *middlewareService) Ctx(r *ghttp.Request) {
	// 初始化，务必最开始执行
	cache := gcache.New()
	adapterRedis := adapter.NewRedis(g.Redis())
	cache.SetAdapter(adapterRedis)
	customCtx := &model.Context{
		Cache:   cache,
		Request: r,
		Data:    make(g.Map),
	}
	shared.Context.Init(r, customCtx)
	// 将自定义的上下文对象传递到模板变量中使用
	r.Assigns(g.Map{
		"Context": customCtx,
	})
	// 执行下一步请求逻辑
	r.Middleware.Next()
}

func (s *middlewareService) SessionAuth(r *ghttp.Request) {
	if userEntity := Session.GetUser(r.Context()); userEntity != nil {
		user := &model.ContextUser{
			Id:      userEntity.Id,
			Account: userEntity.Account,
		}
		shared.Context.SetUser(r.Context(), user)
	} else {
		response.JsonExit(r, 200, "请登录")
	}
	r.Middleware.Next()
}
